# ball.py 物理优化
import pygame
from pygame.math import Vector2
from pygame.sprite import Sprite
import random
import math


class Ball(Sprite):
    def __init__(self, game):
        super().__init__()
        self.config = game.config
        self.screen_width = self.config.screen_width
        self.screen_height = self.config.screen_height
        self.radius = self.config.ball_radius
        self.max_speed = game.config.ball_MAX_SPEED  # 从配置中读取最大速度

        # 矢量速度系统
        self.velocity = Vector2(random.choice([-5, 5]), -5)
        self.damping = 0.98  # 速度衰减系数

        # 创建图像
        self.image = pygame.Surface((self.radius * 2, self.radius * 2), pygame.SRCALPHA)
        pygame.draw.circle(self.image, self.config.colors['red'], (self.radius, self.radius), self.radius)
        self.rect = self.image.get_rect(center=(self.screen_width // 2, self.screen_height // 2))

    def update(self, paddle_rect):
        # 应用阻尼
        self.velocity *= self.damping

        # 限制最小速度
        min_speed = 2.0
        if self.velocity.length() < min_speed:
            self.velocity.scale_to_length(min_speed)

        # 限制最大速度
        if self.velocity.length() > self.max_speed:
            self.velocity.scale_to_length(self.max_speed)

        # 更新位置
        self.rect.center += self.velocity

        # 边界碰撞
        self._handle_wall_collision()

        # 挡板碰撞
        return self._handle_paddle_collision(paddle_rect)

    def _handle_wall_collision(self):
        # 左右墙壁碰撞（保留能量）
        if self.rect.left <= 0 or self.rect.right >= self.screen_width:
            self.velocity.x *= -1
            self.rect.clamp_ip(pygame.Rect(0, 0, self.screen_width, self.screen_height))

        # 顶部碰撞
        if self.rect.top <= 0:
            self.velocity.y *= -1
            self.rect.top = 0

    def _handle_paddle_collision(self, paddle_rect):
        if self.rect.colliderect(paddle_rect):
            # 计算碰撞点偏移量
            offset = (self.rect.centerx - paddle_rect.centerx) / (paddle_rect.width / 2)

            # 限制偏移量范围
            offset = max(min(offset, 1.0), -1.0)

            # 动态调整反弹角度（-45°~45°）
            angle = math.radians(offset * 45)
            speed = max(self.velocity.length(), 3.0)  # 确保最小速度

            # 计算新速度矢量
            new_vx = speed * math.sin(angle)
            new_vy = -speed * math.cos(angle)

            # 防止水平速度过小
            if abs(new_vx) < 2.0:
                new_vx = 2.0 * (1 if new_vx >= 0 else -1)

            self.velocity = Vector2(new_vx, new_vy)

            # 防止粘板
            self.rect.bottom = paddle_rect.top
            return True
        return False

    def reset(self):
        self.rect.center = (self.screen_width // 2, self.screen_height // 2)
        self.velocity = Vector2(random.choice([-5, 5]), -5)

    def scale_to_length(self, length):
        """将速度矢量的长度调整为指定值"""
        self.velocity.scale_to_length(length)
